package cn.itcast.web.controller.cargo;

import cn.itcast.domain.cargo.*;
import cn.itcast.service.cargo.ContractService;
import cn.itcast.service.cargo.ExportProductService;
import cn.itcast.service.cargo.ExportService;
import cn.itcast.vo.ExportProductVo;
import cn.itcast.vo.ExportResult;
import cn.itcast.vo.ExportVo;
import cn.itcast.web.controller.BaseController;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.apache.cxf.jaxrs.client.WebClient;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

@Controller
@RequestMapping("/cargo/export")
public class ExportController extends BaseController {

    @Reference
    private ContractService contractService;
    @Reference
    private ExportService exportService;

    @Reference
    private ExportProductService exportProductService;

    /**
     * 1. 合同管理
     * http://localhost:8080/cargo/export/contractList.do
     */
    @RequestMapping("/contractList")
    public String contractList(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "5") Integer pageSize) {
        /* 需求： 查询状态为1的购销合同*/
        ContractExample example = new ContractExample();
        ContractExample.Criteria criteria = example.createCriteria();
        // 查询条件：company_id
        criteria.andCompanyIdEqualTo(getLoginCompanyId());
        // 查询条件：state
        criteria.andStateEqualTo(1);
        PageInfo<Contract> pageInfo =
                contractService.findByPage(example, pageNum, pageSize);

        request.setAttribute("pageInfo",pageInfo);
        return "cargo/export/export-contractList";
    }

    /**
     * 2. 报运列表
     * http://localhost:8080/cargo/export/list.do
     */
    @RequestMapping("/list")
    public String list(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "5") Integer pageSize) {
        // 条件对象
        ExportExample example = new ExportExample();
        example.setOrderByClause("create_time desc");
        ExportExample.Criteria criteria = example.createCriteria();
        // 查询条件：company_id
        criteria.andCompanyIdEqualTo(getLoginCompanyId());

        // 分页查询
        PageInfo<Export> pageInfo =
                exportService.findByPage(example, pageNum, pageSize);

        request.setAttribute("pageInfo",pageInfo);
        return "cargo/export/export-list";
    }

    /**
     * 3. 进入报运单添加页面
     */
    @RequestMapping("/toExport")
    public String toExport(String id){
        request.setAttribute("id",id);
        return "cargo/export/export-toExport";
    }

    /**
     * 5. 进入修改页面
     */
    @RequestMapping("/toUpdate")
    public String toUpdate(String id) {
        // 根据id查询
        Export export = exportService.findById(id);
        request.setAttribute("export", export);

        // 根据报运单id查询商品
        ExportProductExample example = new ExportProductExample();
        example.createCriteria().andExportIdEqualTo(id);
        List<ExportProduct> eps = exportProductService.findAll(example);
        request.setAttribute("eps",eps);
        return "cargo/export/export-update";
    }

    @RequestMapping("/edit")
    public String edit(Export export){
        export.setCompanyId(getLoginCompanyId());
        export.setCompanyName(getLoginCompanyName());
        if (StringUtils.isEmpty(export.getId())){
            exportService.save(export);
        }else {
            exportService.update(export);
        }
        return "redirect:/cargo/export/list.do";
    }

    @RequestMapping("toView")
    public String toView(String id){
        Export export = exportService.findById(id);
        request.setAttribute("export", export);
        return "cargo/export/export-view";
    }

    /**
     * 6. 提交、取消
     * http://localhost:8080/cargo/export/submit.do?id=4
     * http://localhost:8080/cargo/export/cancel.do?id=4
     */
    @RequestMapping("/submit")
    public String submit(String id){
        Export export = new Export();
        export.setId(id);
        export.setState(1);
        exportService.update(export);
        return "redirect:/cargo/export/list.do";
    }

    @RequestMapping("/cancel")
    public String cancel(String id){
        Export export = new Export();
        export.setId(id);
        export.setState(0);
        exportService.update(export);
        return "redirect:/cargo/export/list.do";
    }

    /**
     * 7. 电子报运，远程访问海关报运平台（模拟：jk_export）
     * http://localhost:8080/cargo/export/exportE.do?id=4
     */
    @RequestMapping("/exportE")
    public String exportE(String id) throws InvocationTargetException, IllegalAccessException {

        // 1.封装请求参数
        ExportVo exportVo = new ExportVo();
        // 1.1 封装报运单
        // 1.1.1 根据报运单id查询
        Export export = exportService.findById(id);
        // 1.1.2 对象拷贝 org.springframework.beans
        BeanUtils.copyProperties(export,exportVo);
        exportVo.setExportId(id);

        // 1.2 封装报运单的商品
        // 1.2.1 获取商品集合
        List<ExportProductVo> products = exportVo.getProducts();
        // 1.2.2 根据报运单id查询商品
        ExportProductExample example = new ExportProductExample();
        example.createCriteria().andExportIdEqualTo(id);
        List<ExportProduct> list = exportProductService.findAll(example);
        if (list != null && list.size()>0){
            for (ExportProduct exportProduct : list) {
                // 1.2.3 封装报运商品
                ExportProductVo exportProductVo = new ExportProductVo();
                //对象拷贝：exportProduct  -->   exportProductVo
                BeanUtils.copyProperties(exportProduct,exportProductVo);
                //设置商品id
                exportProductVo.setExportProductId(exportProduct.getId());
                //设置报运单id
                exportProductVo.setExportId(id);
                //对象添加到集合
                products.add(exportProductVo);
            }
        }

        // 2.远程调用（1）电子报运，海关报运平台的数据库中自动录入报运数据
        WebClient
                .create("http://192.168.110.55:9001/ws/export/user")
                .post(exportVo);

        // 3.远程调用（2）获取报运结果
        ExportResult exportResult =
                WebClient
                        .create("http://192.168.110.55:9001/ws/export/user/"+id)
                        .get(ExportResult.class);

        // 4. 根据报运结果，修改数据库中报运单信息
        exportService.updateExport(exportResult);
        return "redirect:/cargo/export/list.do";
    }
}

